import Vue from 'vue'
import VueRouter from 'vue-router'
import loginIndex from '@/views/login/loginIndex'
import homeIndex from '@/views/home/homeIndex'
import liKeDe from '@/views/likede/liKeDe'
import OperationWorkOrder from '@/views/workorder/OperationWorkOrder'
import MaintenanceWorkOrder from '@/views/workorder/MaintenanceWorkOrder'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: loginIndex
  },
  {
    path: '/',
    name: 'home',
    component: homeIndex,
    redirect: '/likede',
    children: [
      { path: '/likede', component: liKeDe },
      { path: '/operation', component: OperationWorkOrder },
      { path: '/maintenance', component: MaintenanceWorkOrder }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})

export default router
